package softtech.apps.autoanswerphonecall;

import java.io.File;
import java.io.IOException;

import android.media.MediaRecorder;
import android.os.Environment;

public class Recoder {
	
	private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
	private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
	private static final String AUDIO_RECORDER_FOLDER = "VoiceMessage";
	
	private MediaRecorder recorder = null;
	
	
	private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4,
			MediaRecorder.OutputFormat.THREE_GPP };
	private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4,
			AUDIO_RECORDER_FILE_EXT_3GP };
	
//	private File files[];
	
	private int currentFormat = 0;
//	private String filePath;
	
	public String getFilename() {
		String filepath = Environment.getExternalStorageDirectory().getPath();
		File file = new File(filepath, AUDIO_RECORDER_FOLDER);

		if (!file.exists()) {
			file.mkdirs();
		}

		//return (file.getAbsolutePath() + "/" + "Audio-Record-" +System.currentTimeMillis() + file_exts[currentFormat]);
		return (file.getAbsolutePath() + "/" + "voice-message-" +System.currentTimeMillis() + file_exts[currentFormat]);
	}
	
	public void startRecording() {
		this.recorder = new MediaRecorder();
		this.recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
		this.recorder.setOutputFormat(output_formats[currentFormat]);
		this.recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		this.recorder.setOutputFile(getFilename());
		this.recorder.setOnErrorListener(errorListener);
		this.recorder.setOnInfoListener(infoListener);

		try {
			this.recorder.prepare();
			this.recorder.start();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void stopRecording() {
		if (null != this.recorder) {
//			filePath = getFilename();
			this.recorder.stop();
			this.recorder.reset();
			this.recorder.release();

			this.recorder = null;
		}
	}
	
	private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
		@Override
		public void onError(MediaRecorder mr, int what, int extra) {
//			Toast.makeText(VoiceManagerActivity.this,
//					"Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
		}
	};

	private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
		@Override
		public void onInfo(MediaRecorder mr, int what, int extra) {
//			Toast.makeText(VoiceManagerActivity.this,
//					"Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
//					.show();
		}
	};

	
	
}
